package org.vyana.model {
	
	import flash.display.BitmapData;
	
	import mx.core.BitmapAsset;
	import mx.core.SoundAsset;
	
	import org.vyana.control.*;
	import org.vyana.model.*;
	import org.vyana.model.modules.*;
	import org.vyana.model.vo.ThemeModuleDescriptor;

	public class VyanaThemesManager extends VyanaManager {		
		
		public var themeDescriptor:ThemeModuleDescriptor;
		
		function VyanaThemesManager() {
			VyanaContext.getInstance().addEventListener(VyanaModuleEvent.THEME_MODULE_READY, onThemeModuleReady);
		}
		
		protected function onThemeModuleReady(e:VyanaEvent):void {
			var md:ThemeModuleDescriptor = e.data as ThemeModuleDescriptor;			
			
			// Same module loaded? do nothing
			if (themeDescriptor == md)
				return;			
			
			// Unload old set new
			if (themeDescriptor)
				themeDescriptor.unload();
			
			themeDescriptor = md;
		}
		
		public function playSound(id:String):void {			
			var sndCls:Class = getResource(id);
			if (!sndCls) return;
			var snd:SoundAsset = new sndCls() as SoundAsset;
			snd.play();  		  	
		}		
		
		public function getColor(id:String):uint {
			
			if (themeDescriptor)
				return themeDescriptor.themeModule.getColor(id);
			
			return null;
		}
		
		public function getBitmapData(id:String):BitmapData {
			var result:BitmapData;
			var cls:Class = getResource(id);
			var ba:BitmapAsset = cls ? new cls() : null;
			
			if (ba)
				result = ba.bitmapData;
			
			return result;
		}
		
		public function getResource(id:String):* {
			var res:*;
			
			if (themeDescriptor)
				res = themeDescriptor.themeModule.getResource(id);
			
			if (!res)
				model.modulesManager.enumResourceModules(
					function (m:BaseResourceModule):void {
						
						if (!res)
							res = m.getResource(id);
					}
				);
			
			return res;
		}		
	}
}